package net.hn.hnms.sys.system.controller;

import cn.dev33.satoken.secure.BCrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.constant.UserConstants;
import net.hn.hnms.sys.common.core.domain.ApiResult;
import net.hn.hnms.sys.common.core.domain.R;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.core.web.controller.BaseController;
import net.hn.hnms.sys.system.api.domain.SysDept;
import net.hn.hnms.sys.system.api.domain.SysUser;
import net.hn.hnms.sys.system.request.OneAccessOrgReq;
import net.hn.hnms.sys.system.request.OneAccessUserReq;
import net.hn.hnms.sys.system.service.ISysDeptService;
import net.hn.hnms.sys.system.service.ISysUserService;
import net.hn.hnms.sys.system.vo.OneAccessUserVo;
import net.hn.hnms.sys.system.vo.OneAccessVo;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Validated
@Api(value = "华为", tags = {"OneAccess管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/oneAccess")
public class OneAccessController  extends BaseController {

    private final ISysDeptService deptService;

    private final ISysUserService userService;

    @ApiOperation("机构创建")
    @PostMapping("/OrgCreateService")
    public ApiResult<OneAccessVo> orgCreateService(@RequestBody OneAccessOrgReq req) {
        authenticate(req.getCreateBy(),req.getIamRemotePwd());

        SysDept dept = new SysDept();
        BeanUtils.copyProperties(req,dept);
        dept.setParentId(Long.parseLong(req.getParentId()));
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return ApiResult.failure(req.getIamRequestId(), Constants.FAIL+"","新增机构" + dept.getDeptName() + "失败，机构名称已存在");
        }
        int i = deptService.insertDept(dept);
        if (i > 0) {
            OneAccessVo o = new OneAccessVo();
            o.setIamRequestId(req.getIamRequestId());
            o.setOrgId(dept.getDeptId().toString());
            o.setResultCode("0");
            return ApiResult.success(req.getIamRequestId(),null,dept.getDeptId().toString());
        }
        return ApiResult.failure(req.getIamRequestId(), Constants.FAIL+"","新增机构'" + dept.getDeptName() + "'失败");
    }

    @ApiOperation("机构修改")
    @PostMapping("/OrgUpdateService")
    public ApiResult<OneAccessVo> orgUpdateService(@RequestBody OneAccessOrgReq req) {
        authenticate(req.getCreateBy(),req.getIamRemotePwd());


        SysDept dept = new SysDept();
        Long deptId = Long.parseLong(req.getDeptId());

        BeanUtils.copyProperties(req,dept);
        dept.setDeptId(deptId);
        dept.setParentId(Long.parseLong(req.getParentId()));
        deptService.checkDeptDataScope(deptId);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return ApiResult.failure(req.getIamRequestId(),Constants.FAIL+"","修改机构'" + dept.getDeptName() + "'失败，机构名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return ApiResult.failure(req.getIamRequestId(),Constants.FAIL+"","修改机构'" + dept.getDeptName() + "'失败，上级机构不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return ApiResult.failure(req.getIamRequestId(),Constants.FAIL+"","该机构包含未停用的子机构！");
        }
        int i = deptService.updateDept(dept);
        if (i > 0) {
            OneAccessVo o = new OneAccessVo();
            o.setIamRequestId(req.getIamRequestId());
            o.setOrgId(dept.getDeptId().toString());
            o.setResultCode("0");
            return ApiResult.success(req.getIamRequestId(),null,dept.getDeptId().toString());
        }
        return ApiResult.failure(req.getIamRequestId(), Constants.FAIL+"","修改机构'" + dept.getDeptName() + "'失败");
    }

    @ApiOperation("机构删除")
    @PostMapping("/OrgDeleteService")
    public ApiResult<OneAccessVo> orgDeleteService(@RequestBody OneAccessOrgReq req) {
        authenticate(req.getCreateBy(),req.getIamRemotePwd());

        SysDept dept = new SysDept();
        Long deptId = Long.parseLong(req.getDeptId());
        BeanUtils.copyProperties(req,dept);
        dept.setDeptId(deptId);
        if (deptService.hasChildByDeptId(deptId)) {
            return ApiResult.failure(req.getIamRequestId(), Constants.FAIL+"","存在下级机构,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return ApiResult.failure(req.getIamRequestId(), Constants.FAIL+"","机构存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        int i = deptService.deleteDeptById(deptId);
        if (i > 0) {
            OneAccessVo o = new OneAccessVo();
            o.setIamRequestId(req.getIamRequestId());
            o.setOrgId(dept.getDeptId().toString());
            o.setResultCode("0");
            return ApiResult.success(req.getIamRequestId(),null,dept.getDeptId().toString());
        }
        return ApiResult.failure(req.getIamRequestId(), Constants.FAIL+"","删除机构'" + dept.getDeptName() + "'失败");
    }



    @ApiOperation("获取部门表和用户表字段信息")
    @PostMapping("/SchemaService")
    public R<Map<String, Object>> getDeptAndUserColumnInfo(@RequestBody OneAccessUserReq req){
        authenticate(req.getIamRemoteUser(),req.getIamRemotePwd());

        return R.ok(deptService.getDeptAndUserColumnInfo(req));
    }


    @PostMapping(value = "/UserCreateService")
    @ApiOperation("OneAccess用户创建接口")
    public ApiResult<OneAccessUserVo> UserCreateService(@RequestBody OneAccessUserReq req){
        authenticate(req.getIamRemoteUser(),req.getIamRemotePwd());


        SysUser sysUser = new SysUser();
        sysUser.setPhonenumber(req.getPhonenumber());
        sysUser.setUserName(req.getUserName());
        sysUser.setEmail(req.getEmail());

        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(req.getUserName()))) {
            return ApiResult.failure(req.getIamRequestId(), Constants.FAIL+"","新增用户'" + req.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(req.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(sysUser))) {
            return ApiResult.failure(req.getIamRequestId(),Constants.FAIL+"","新增用户'" + req.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(req.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(sysUser))) {
            return ApiResult.failure(req.getIamRequestId(),Constants.FAIL+"","新增用户'" + req.getUserName() + "'失败，邮箱账号已存在");
        }
        req.setPassword(BCrypt.hashpw(req.getPassword()));
        OneAccessUserVo v =  userService.insertUserOneAccess(req);
        return ApiResult.success(req.getIamRequestId(),v.getUid(),"");
    }

    @PostMapping(value = "/UserUpdateService")
    @ApiOperation("OneAccess用户修改接口")
    public ApiResult<OneAccessUserVo> userUpdateService(@RequestBody OneAccessUserReq req){
        authenticate(req.getIamRemoteUser(),req.getIamRemotePwd());
        return ApiResult.success(userService.updateUserOneAccess(req).getIamRequestId(),"","");
    }


    @PostMapping(value = "/UserDeleteService")
    @ApiOperation("OneAccess用户删除接口")
    public ApiResult<OneAccessUserVo> userDeleteService(@RequestBody OneAccessUserReq req){
        authenticate(req.getIamRemoteUser(),req.getIamRemotePwd());

        return ApiResult.success(userService.deleteUserOneAccess(req).getIamRequestId(),"","");
    }


    public void authenticate(String username, String password) throws IllegalArgumentException {
        // 在这里编写验证逻辑，例如与数据库或其他身份验证系统进行比对
        // 这里只是一个示例，你需要根据实际情况进行相应的实现
        if (!username.equals("admin") || !password.equals("hn@2022")) {
            throw new IllegalArgumentException("账号或密码错误");
        }
        // 验证成功，继续执行后续操作
    }



}
